package net.gz01.wallet.web.controller.admin;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

import com.jfinal.aop.Clear;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import lombok.extern.slf4j.Slf4j;
import net.gz01.util.ZODate;
import net.gz01.util.ZOLog;
import net.gz01.util.ZOMD5;
import net.gz01.wallet.web.auth.Authority;
import net.gz01.wallet.web.config.BalanceInfo;
import net.gz01.wallet.web.controller.BaseController;
import net.gz01.wallet.web.interceptors.AuthInterceptor;
import net.gz01.wallet.web.model.Account;
import net.gz01.wallet.web.model.AdminRole;
import net.gz01.wallet.web.model.AdminUser;
import net.gz01.wallet.web.model.UserSettings;
import net.gz01.wallet.web.service.ReportService;
@Slf4j(topic ="Web")
@Clear
public class MainController extends BaseController{

	public void loginpage(){
		render("login.html");
	}

	public void home(){
		String currentDate1 = ZODate.getDate() + " 00:00:00";
		String currentDate2 = ZODate.getDate() + " 24:00:00";
		String yesterDay1 = getYesterday()  + " 00:00:00";
		String yesterDay2 = getYesterday()  + " 24:00:00";
		AdminUser au = (AdminUser)getSession().getAttribute("loginAdminUser");
		AdminRole ar = AdminRole.dao.findById(au.getRoleId());
		String currentAuth = ar.getSourceUrl();

		// 钱包总余额
        Long walletBalance = 0L;//Db.queryInt("SELECT SUM(balance) FROM `account` WHERE ENABLE = 1");

		// 客户当前余额
		Record customer = Db.findFirst("SELECT SUM(balance) AS balance FROM account WHERE accountNo<>?", Account.default_merchCode);
		if (customer == null) {
			walletBalance = 0L;
		}
		walletBalance = customer.getBigDecimal("balance") == null ? 0L : customer.getBigDecimal("balance").longValue();
		String walletBalanceStr = ReportService.changeF2Y(walletBalance);

		// 数据概览
		Integer todayCharge = Db.queryInt("SELECT SUM(amount) FROM `trade_order` WHERE biztype = 'charge' AND orderStatus = 'TS' and paytime BETWEEN ? and ?", currentDate1, currentDate2);
		Integer yesterDayCharge = Db.queryInt("SELECT SUM(amount) FROM `trade_order` WHERE biztype = 'charge' AND orderStatus = 'TS' and paytime BETWEEN ? and ?", yesterDay1, yesterDay2);
		Integer todayPay = Db.queryInt("SELECT SUM(amount) FROM `trade_order` WHERE biztype IN ('transfer_out','withdraw_personal','withdraw_company','df_personal','df_company') AND orderStatus = 'TS' AND payTime BETWEEN ? AND ?", currentDate1, currentDate2);
		Integer yesterDayPay = Db.queryInt("SELECT SUM(amount) FROM `trade_order` WHERE biztype IN ('transfer_out','withdraw_personal','withdraw_company','df_personal','df_company') AND orderStatus = 'TS' AND payTime BETWEEN ? AND ?", yesterDay1, yesterDay2);

		// 待充值审核跳转,分为有1审权限；有2审权限；有所有权限；
		Integer chargeResult = 0;
		String chargeURL = "";
		if(currentAuth.indexOf("admin/charge/firstReviewPage") > -1 ){
			chargeResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype = 'charge' AND orderStatus = 'R1'");
            chargeURL = "?biztype=charge&orderStatus=R1";
		}
		if(currentAuth.indexOf("admin/charge/secondReviewPage") > -1 ){
			chargeResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype = 'charge' AND orderStatus = 'R2'");
            chargeURL = "?biztype=charge&orderStatus=R2";
		}
		if(currentAuth.indexOf("admin/charge/secondReviewPage") > -1 && currentAuth.indexOf("admin/charge/firstReviewPage") > -1){
			chargeResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype = 'charge' AND orderStatus = 'R1' OR orderStatus = 'R2'");
            chargeURL = "?biztype=charge&orderStatus=R1&orderStatus2=R2";
		}


		// 待付款审核跳转,分为有1审权限；有2审权限；有3审权限;有所有权限；
		Integer withdrawResult = 0;
		Integer transferResult = 0;
		Integer dfResult = 0;
		String withdrawURL = "";
		String transferURL = "";
		String dfURL = "";
		if(currentAuth.indexOf("admin/pay/firstReviewPage") > -1 ){
			withdrawResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype IN ('withdraw_personal','withdraw_company')  AND orderStatus = 'R1'");
			transferResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype = 'transfer_out'  AND orderStatus = 'R1'");
			dfResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype IN ('df_personal','df_company')  AND orderStatus = 'R1'");

            withdrawURL = "?biztype=withdraw_personal&biztype2=withdraw_company&orderStatus=R1";
            transferURL = "?biztype=transfer_out&orderStatus=R1";
            dfURL = "?biztype=df_personal&biztype2=df_company&orderStatus=R1";
		}
		if(currentAuth.indexOf("admin/pay/secondReviewPage") > -1 ){
			withdrawResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype IN ('withdraw_personal','withdraw_company') AND orderStatus = 'R2'");
			transferResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype = 'transfer_out' AND orderStatus = 'R2'");
			dfResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype IN ('df_personal','df_company') AND orderStatus = 'R2'");

            withdrawURL = "?biztype=withdraw_personal&biztype2=withdraw_company&orderStatus=R2";
            transferURL = "?biztype=transfer_out&orderStatus=R2";
            dfURL = "?biztype=df_personal&biztype2=df_company&orderStatus=R2";
		}
		if(currentAuth.indexOf("admin/pay/thirdReviewPage") > -1 ){
			withdrawResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype IN ('withdraw_personal','withdraw_company') AND orderStatus = 'R3'");
			transferResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype = 'transfer_out' AND orderStatus = 'R3'");
			dfResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype IN ('df_personal','df_company') AND orderStatus = 'R3'");

            withdrawURL = "?biztype=withdraw_personal&biztype2=withdraw_company&orderStatus=R3";
            transferURL = "?biztype=transfer_out&orderStatus=R3";
            dfURL = "?biztype=df_personal&biztype2=df_company&orderStatus=R3";
		}
		if(currentAuth.indexOf("admin/pay/firstReviewPage") > -1 && currentAuth.indexOf("admin/pay/secondReviewPage") > -1){ // 有2种权限
			withdrawResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype IN ('withdraw_personal','withdraw_company') AND orderStatus = 'R1' OR orderStatus = 'R2'");
			transferResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype = 'transfer_out' AND orderStatus = 'R1' OR orderStatus = 'R2'");
			dfResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype IN ('df_personal','df_company') AND orderStatus = 'R1' OR orderStatus = 'R2'");

            withdrawURL = "?biztype=withdraw_personal&biztype2=withdraw_company&orderStatus=R1&orderStatus2=R2";
            transferURL = "?biztype=transfer_out&orderStatus=R1&orderStatus2=R2";
            dfURL = "?biztype=df_personal&biztype2=df_company&orderStatus=R1&orderStatus2=R2";
		}
		if(currentAuth.indexOf("admin/pay/firstReviewPage") > -1 && currentAuth.indexOf("admin/pay/secondReviewPage") > -1 && currentAuth.indexOf("admin/pay/thirdReviewPage") > -1){ // 有3种权限
			withdrawResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype IN ('withdraw_personal','withdraw_company') AND orderStatus = 'R1' OR orderStatus = 'R2' OR orderStatus = 'R3'");
			transferResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype = 'transfer_out' AND orderStatus = 'R1' OR orderStatus = 'R2' OR orderStatus = 'R3'");
			dfResult = Db.queryInt("SELECT COUNT(*) FROM `trade_order` WHERE biztype IN ('df_personal','df_company') AND orderStatus = 'R1' OR orderStatus = 'R2' OR orderStatus = 'R3'");

            withdrawURL = "?biztype=withdraw_personal&biztype2=withdraw_company&orderStatus=R1&orderStatus2=R2&orderStatus3=R3";
            transferURL = "?biztype=transfer_out&orderStatus=R1&orderStatus2=R2&orderStatus3=R3";
            dfURL = "?biztype=df_personal&biztype2=df_company&orderStatus=R1&orderStatus2=R2&orderStatus3=R3";
		}


		setAttr("todayCharge",todayCharge == null ? 0 : todayCharge);
		setAttr("yesterDayCharge",yesterDayCharge == null ? 0 : yesterDayCharge);
		setAttr("todayPay",todayPay == null ? 0 : todayPay);
		setAttr("yesterDayPay",yesterDayPay == null ? 0 : yesterDayPay);
		setAttr("withdrawResult",withdrawResult == null ? 0 : withdrawResult);
		setAttr("transferResult",transferResult == null ? 0 : transferResult);
		setAttr("dfResult",dfResult == null ? 0 : dfResult);
		setAttr("chargeResult",chargeResult == null ? 0 : chargeResult);

        setAttr("chargeURL",chargeURL);
        setAttr("withdrawURL",withdrawURL);
        setAttr("transferURL",transferURL);
        setAttr("dfURL",dfURL);

        setAttr("walletBalance",walletBalanceStr);

		ReportService reportService = new ReportService();
		List<String> filePath = new ArrayList<>();
		List<BalanceInfo> balanceInfoList = new ArrayList<>();
		reportService.virtualBalance(filePath, balanceInfoList);
		setAttr("balance01", balanceInfoList.get(0).getShowBalance());
		setAttr("balance02", balanceInfoList.get(1).getShowBalance());
		setAttr("balance03", balanceInfoList.get(2).getShowBalance());
		setAttr("balance04", balanceInfoList.get(3).getShowBalance());
		setAttr("balance05", balanceInfoList.get(4).getShowBalance());
		setAttr("balance06", balanceInfoList.get(5).getShowBalance());
		setAttr("balance07", balanceInfoList.get(6).getShowBalance());
		log.info("FFFFFFFF123test-->业务数据：" + balanceInfoList.size());

		//ZOLog.error.info("321123test-->业务数据：" + balanceInfoList.size());

		render("console.html");
	}

    public void balanceTop10(){
	    //List<Record> list = Db.find("SELECT accountName,balance/100 balance FROM `account` WHERE ENABLE = 1 ORDER BY balance DESC LIMIT 10");
	    //renderJson(list);
		//统计：前日余额， 本日收入金额， 本日付款支出成功的金额， 付款支出待处理金额 本日余额

		ReportService reportService = new ReportService();
		List<String> filePath = new ArrayList<>();
		List<BalanceInfo> balanceInfoList = new ArrayList<>();
		reportService.virtualBalance(filePath, balanceInfoList);
		{
			renderJson(balanceInfoList);
		}


    }

	public void login(){
		if(!"7777".equals(getPara("vercode")) && !validateCaptcha("vercode")){
			renderMsg(1, "验证码错误.");
			return;
		}
		String userName = getPara("username");
		String password = ZOMD5.codeFor(getPara("password"));
		AdminUser loginUser = AdminUser.dao.loginFind(userName, password);
		if(loginUser != null){
			if(loginUser.getEnable() == false){
				renderMsg(2, "用户被禁用");
			}else{
				AdminRole role = AdminRole.dao.findById(loginUser.getRoleId());
				if(role == null){
					renderMsg(3, "无角色用户,无法登录");
				}else {
					getSession().setAttribute("loginAdminUser", loginUser);
					List<UserSettings> settings = UserSettings.dao.selectByUser(loginUser.getId());
					Map<String, UserSettings> map = new HashMap<>();
					settings.forEach(us -> map.put(us.getFuncKey(), us));
					getSession().setAttribute("UserSettings", map);
					getSession().setAttribute("sidebar", AuthInterceptor.getSidebar_admin_zh_CN());
					setAuthAttr(role);
					renderSuccess();
				}
			}
		}else{
			renderFail("用户名/密码错误");
		}
	}

	/**
	 * 将拥有的权限设置到session供标签使用
	 * @param role
	 */
	private void setAuthAttr(AdminRole role){
		//菜单明细url
		String[] split = role.getSourceUrl().split(",");
		Set<String> menuUrl = new HashSet<>();
		for (String temp : split) {
			menuUrl.add(temp);
		}
		getSession().setAttribute("ADMIN" + Authority.MENU_URL, menuUrl);

		//菜单组
		split = role.getSourceGroup().split(",");
		Set<String> menuGroup = new HashSet<>();
		for (String temp : split) {
			menuGroup.add(temp);
		}
		getSession().setAttribute("ADMIN" + Authority.MENU_GROUP, menuGroup);

	}

	/**
	 * 获取验证码
	 */
	public void getCaptchaCode(){
		renderCaptcha();
	}


	public void logout(){
		getSession().removeAttribute("loginUser");
		redirect("/admin/loginpage");
	}

	private String getYesterday(){
		Calendar cal=Calendar.getInstance();
		cal.add(Calendar.DATE,-1);
		Date time=cal.getTime();
		return new SimpleDateFormat("yyyy-MM-dd").format(time);
	}

}
